/*
 * @Description:
 * @Author: lixx
 * @Date: 2025-08-19 16:16:05
 * @LastEditTime: 2025-08-27 15:47:48
 * @LastEditors: lixx
 */
const express = require("express");
const fs = require("fs");
const path = require("path");
const mammoth = require("mammoth");
const app = express();
const port = 3000;
let docContent = "";

const targetFilePath = path.join(
  __dirname,
  "./docs/1. HTML语义：div和span不是够用了吗？.docx"
);

async function loadDocumentText() {
  try {
    // 优先支持 .txt；.docx 用 mammoth；.doc 不支持
    const exists = fs.existsSync(targetFilePath);
    if (!exists) {
      const txtPath = path.join(__dirname, "./docs/test.txt");
      if (fs.existsSync(txtPath)) {
        docContent = fs.readFileSync(txtPath, "utf-8");
        console.log("Loaded text from test.txt");
        return;
      }
      console.warn("目标文件不存在，且 test.txt 不存在");
      docContent = "";
      return;
    }

    const ext = path.extname(targetFilePath).toLowerCase();
    if (ext === ".txt") {
      docContent = fs.readFileSync(targetFilePath, "utf-8");
    } else if (ext === ".docx") {
      const result = await mammoth.extractRawText({ path: targetFilePath });
      docContent = result.value || "";
    } else if (ext === ".doc") {
      console.error(".doc 二进制格式不受支持，请转换为 .docx 或 .txt");
      docContent = "请将文档转换为 .docx 或 .txt 后重试";
    } else {
      console.error(`不支持的文件类型: ${ext}`);
      docContent = "不支持的文件类型";
    }
  } catch (error) {
    console.error("加载文档失败:", error);
    docContent = "文档加载失败";
  }
}

// 启动前预加载文本（异步）
loadDocumentText().then(() => {
  console.log("Document loaded. Length:", docContent.length);
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

app.get("/getReqText", (req, res) => {
  // 设置响应头
  res.set({
    "Content-Type": "text/event-stream", // 高速浏览器这是一个sse（server sent events）流，而不是普通的http请求
    "Cache-Control": "no-cache", // 禁止缓存
    Connection: "keep-alive", // 保持连接
  });
  // 发送请求头
  // 把响应头发送给客户端，建立sse通道，这样客户端就能马上开始接收数据，而不是等到服务端响应结束
  res.flushHeaders();
  const content = [...(docContent || "")];
  let index = 0;
  let timer = setInterval(() => {
    res.write(`data: ${content[index]} \n\n`);
    index++;
    console.log(index);
    console.log(content.length);
    if (index >= content.length) {
      clearInterval(timer);
      timer = null;
      res.write(`data: end \n\n`);
      //res.end();
    }
  }, 200);
});
